/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 4/16/2011
*/

global class CaseBusinessDayAgeScheduler implements Schedulable, Database.Batchable<sObject>, Database.Stateful{
	/* To schedule it at 7:00am EST every day , in Anonymous Blocks and execute below commands
	   Boolean IS_ALL = false;
	   CaseBusinessDayAgeScheduler a0 = new CaseBusinessDayAgeScheduler(IS_ALL);
	   String sch0 = CaseBusinessDayAgeScheduler.CRON_EXP_WEST_User_Schedule;
	   System.schedule('Batch Update Business Day Age at 7:00am EST daily', sch0, a0);	
	*/
	
	// uses the user's timezone for the basis of all schedules, choose one of below
	public static String CRON_EXP_WEST_User_Schedule      = '0 00 4 * * ?'; // If User TIMEZONESIDKEY = 'America/Los_Angeles'
    public static String CRON_EXP_Mountain_User_Schedule  = '0 00 5 * * ?'; // If User TIMEZONESIDKEY = 'America/Phoenix'
    public static String CRON_EXP_Central_User_Schedule   = '0 00 6 * * ?'; // If User TIMEZONESIDKEY = 'America/Chicago'
    public static String CRON_EXP_East_User_Schedule      = '0 00 7 * * ?'; // If User TIMEZONESIDKEY = 'America/New_York'
    private String query; 
    
	global void execute (SchedulableContext SC){
		ID batchUpdateCaseId = Database.executeBatch(this);
	}	
		
	global CaseBusinessDayAgeScheduler(Boolean isUpdateAll){
		this.query = ' select Start_Date__c, ParentCase__r.RecordType.Name, End_Date__c from Case_Cycle__c ';
		if(!isUpdateAll){
			this.query += ' where End_Date__c = null ';
		}
	}
		
	global Database.QueryLocator start(Database.BatchableContext BC){
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext BC, list<Sobject> scope){
		list<Case_Cycle__c> cclist = new List<Case_Cycle__c>();
		for(Sobject obj : scope){
			Case_Cycle__c cc = (Case_Cycle__c) obj;
			CaseBusinessDayHelper.calculateBusinessAges(cc);
			cclist.add(cc);
		}
		if(!cclist.isEmpty()){
			update cclist; 
		}
	}
	
	global void finish(Database.BatchableContext BC){
	}
}